<?php
/**
 * 基础物料模型层
 *
 * @author kamisama.xia@gmail.com
 * @version 0.1
 */

class material_mdl_basic_material extends dbeav_model{

    var $defaultOrder = array('bm_id',' DESC');

    /**
     * 基础物料列表项扩展字段
     */
    function extra_cols(){
        return array(
            'column_cost' => array('label'=>'成本价','width'=>'75','func_suffix'=>'cost'),
            'column_retail_price' => array('label'=>'售价','width'=>'75','func_suffix'=>'retail_price'),
            'column_weight' => array('label'=>'重量','width'=>'75','func_suffix'=>'weight'),
            'column_unit' => array('label'=>'包装单位','width'=>'75','func_suffix'=>'unit'),
            'column_autosplit' => array('label'=>'是否自动拆单','width'=>'75','func_suffix'=>'autosplit'),
            'column_barcode' => array('label'=>'条形码','width'=>'125','func_suffix'=>'barcode'),
            'column_specifications' => array('label'=>'物料规格','width'=>'120','func_suffix'=>'specifications'),
            'column_brand' => array('label'=>'物料品牌','width'=>'120','func_suffix'=>'brand'),
            'column_volume' => array('label'=>'体积','width'=>'120','func_suffix'=>'volume'),
        );
    }

    /**
     * 条码扩展字段格式化
     */
    function extra_barcode($rows){
        return kernel::single('material_extracolumn_basicmaterial_barcode')->process($rows);
    }

    /**
     * 成本扩展字段格式化
     */
    function extra_cost($rows){
        return kernel::single('material_extracolumn_basicmaterial_cost')->process($rows);
    }

    /**
     * 售价扩展字段格式化
     */
    function extra_retail_price($rows){
        return kernel::single('material_extracolumn_basicmaterial_retailprice')->process($rows);
    }

    /**
     * 重量扩展字段格式化
     */
    function extra_weight($rows){
        return kernel::single('material_extracolumn_basicmaterial_weight')->process($rows);
    }

    /**
     * 包装单位扩展字段格式化
     */
    function extra_unit($rows){
        return kernel::single('material_extracolumn_basicmaterial_unit')->process($rows);
    }

    /**
     * 是否自动拆分扩展字段格式化
     */
    function extra_autosplit($rows){
        return kernel::single('material_extracolumn_basicmaterial_autosplit')->process($rows);
    }

    /**
     * 物料规格字段格式化
     */
    function extra_specifications($rows){
        return kernel::single('material_extracolumn_basicmaterial_specifications')->process($rows);
    }

    /**
     * 体积扩展字段格式化
     */
    function extra_volume($rows){
        return kernel::single('material_extracolumn_basicmaterial_volume')->process($rows);
    }

    /**
     * 物料品牌字段格式化
     */
    function extra_brand($rows){
        return kernel::single('material_extracolumn_basicmaterial_brand')->process($rows);
    }

    /**
     * 物料类型字段格式化
     * @param string $row 物料类型字段
     * @return string
     */
    function modifier_type($row){
        if($row == '1'){
            return '普通';
        }elseif($row == '2'){
            return '组合';
        }
    }

    /**
     * 物料是否可见字段格式化
     * @param string $row 物料是否可见字段
     * @return string
     */
    function modifier_visibled($row){
        if($row == '1'){
            return '在售';
        }elseif($row == '2'){
            return '停售';
        }
    }
    
    /**
     * 是否全渠道字段格式化
     * 
     * @param string $row
     * @return string
     */
    function modifier_omnichannel($row){
        if($row == '1'){
            return '开启';
        }
        else 
        {
            return '关闭';
        }
    }

    /**
     * 导入模板的标题
     *
     * @param Null
     * @return Array
     */
    function exportTemplate($filter){
        foreach ($this->io_title($filter) as $v){
            $title[] = kernel::single('base_charset')->utf2local($v);
        }
        return $title;
    }

    /**
     * 导入导出的标题
     *
     * @param Null
     * @return Array
     */
    function io_title( $filter, $ioType='csv' ){
        switch( $filter ){
            case 'basicM':
                $this->oSchema['csv'][$filter] = array(
                    '*:基础物料名称' => 'material_name',
                    '*:基础物料编码' => 'material_bn',
                    '*:基础物料属性' => 'material_type',
                    '*:条码' => 'barcode',
                    '*:是否在售' => 'visibled',
                    '*:计量单位' => 'unit',
                    '*:销售价' => 'retail_price',
                    '*:成本价' => 'cost',
                    '*:重量' => 'weight',
                    '*:组合类物料信息' => 'bind_info',
                    '*:是否启用保质期监控' => 'use_expire',
                    '*:预警天数配置' => 'warn_day',
                    '*:自动退出库存天数配置' => 'quit_day',
                    '*:基础物料类型' => 'specifications',
                    '*:规格' => 'cat_id',
                    '*:品牌' => 'brand_id',
                    
                    '*:特殊扫码配置' => 'special_setting',
                    '*:特殊扫码开始位数' => 'special_first_num',
                    '*:特殊扫码结束位数' => 'special_last_num',
                    '*:是否自动生成销售物料' => 'create_material_sales',
                    '*:是否全渠道' => 'omnichannel',                );
                break;
            case 'exportBasicM':
                $this->oSchema['csv'][$filter] = array(
                    '*:基础物料名称' => 'material_name',
                    '*:基础物料编码' => 'material_bn',
                    '*:物料属性' => 'material_type',
                    '*:销售状态' => 'visible',
                    '*:重量' => 'weight',
                    '*:物料规格' => 'specifications',
                    '*:物料品牌' => 'brand_id',
                    '*:成本' => 'cost',
                    '*:售价' => 'retail_price',
                    '*:包装单位' => 'unit',
                    '*:是否拆单' => 'autosplit',
                );
                break;
        }
        $this->ioTitle[$ioType][$filter] = array_keys( $this->oSchema[$ioType][$filter] );
        return $this->ioTitle[$ioType][$filter];
    }


    /**
     * 准备导入的参数定义
     *
     * @param Null
     * @return Null
     */
    function prepared_import_csv(){
        $this->ioObj->cacheTime = time();
    }

    /**
     * 准备导入的数据主体内容部分检查和处理
     *
     * @param Array $data
     * @param Boolean $mark
     * @param String $tmpl
     * @param String $msg
     * @return Null
     */
    function prepared_import_csv_obj($data,$mark,$tmpl,&$msg = ''){
        return null;
    }

    /**
     * 准备导入的数据明细内容部分检查和处理
     *
     * @param Array $row
     * @param String $title
     * @param String $tmpl
     * @param Boolean $mark
     * @param Boolean $newObjFlag
     * @param String $msg
     * @return Null
     */
    function prepared_import_csv_row($row,$title,&$tmpl,&$mark,&$newObjFlag,&$msg){

        if (empty($row)){
            return true;
        }
        $mark = false;
        
        $basicMaterialObj = app::get('material')->model('basic_material');
        $salesMaterialObj = app::get('material')->model('sales_material');
        $checkBasicLib    = kernel::single('material_basic_check');#检查数据有效性Lib类
        
        if( substr($row[0],0,1) == '*' ){
            $titleRs =  array_flip($row);
            $mark = 'title';
            
            #[防止重复]记录组织编码
            $this->material_bn_list      = array();
            $this->material_code_list    = array();
            $this->basicm_nums           = 1;
            
            return $titleRs;
        }else{
            $re = base_kvstore::instance('basic_material')->fetch('basic-'.$this->ioObj->cacheTime,$fileData);

            if( !$re ) $fileData = array();

            if(!$row[0]){
                $msg['error'] = "基础物料名称必须填写,物料编码：". $row[1];
                return false;
            }

            if(!$row[1]){
                $msg['error'] = "基础物料编码必须填写,物料名称：". $row[0];
                return false;
            }

            if(!$row[2]){
                $msg['error'] = "基础物料属性必须填写,物料编码：". $row[1];
                return false;
            }

            if(!$row[3]){
                $msg['error'] = "条码必须填写,物料编码：". $row[1];
                return false;
            }

            if(!$row[4]){
                $msg['error'] = "是否在售必须填写,物料编码：". $row[1];
                return false;
            }

            if(isset($this->basicm_nums)){
                $this->basicm_nums ++;
                if($this->basicm_nums > 5000){
                    $msg['error'] = "导入的数量量过大,请减少到5000个以下！";
                    return false;
                }
            }

            #[防止重复]检查物料编号
            if(in_array($row[1], $this->material_bn_list))
            {
                $msg['error'] = 'Line '.$this->basicm_nums.'：物料编号【'. $row[1] .'】重复！';
                return false;
            }
            $this->material_bn_list[]    = $row[1];
            
            #[防止重复]检查物料条码
            if(in_array($row[3], $this->material_code_list))
            {
                $msg['error'] = 'Line '.$this->basicm_nums.'：物料条码【'. $row[0] .'】重复！';
                return false;
            }
            $this->material_code_list[]    = $row[3];
            
            #数据检查
            if($row[4] =="在售"){
                $row[4] = 1;
            }elseif($row[4] =="停售"){
                $row[4] = 2;
            }else{
                $msg['error'] = "是否在售填写的内容错误：".$row[4].",请填写在售或停售,物料编码：". $row[1];
                return false;
            }
            
            //基础物料类型判断
            if(!empty($row[13])){
                $goods_type_obj = app::get('ome')->model('goods_type');
                $typeRow    = $goods_type_obj->dump(array('name'=>$row[13]), 'type_id');
                
                if($typeRow){
                    $row[13] = $typeRow['type_id'];
                } else {
                    $msg['error'] = "基础物料类型：".$row[13]." 不存在,物料编码：". $row[1];
                    return false;
                }
            }

            // 基础物料品牌判断
            if(!empty($row[15])){
                $brand_obj    = app::get('ome')->model('brand');
                $brandRow     = $brand_obj->dump(array('brand_name'=>$row[15]), 'brand_id');
                
                if($brandRow){
                    $row[15]    = $brandRow['brand_id'];
                } else {
                    $msg['error'] = "基础物料品牌：".$row[15]." 不存在,物料编码：". $row[1];
                    return false;
                }
            }

            if($row[2] =="普通"){
                $row[2] = 1;
            }elseif($row[2] =="组合"){
                $row[2] = 2;
            }else{
                $msg['error'] = "基础物料属性填写的内容错误：".$row[2].",请填写普通或组合,物料编码：". $row[1];
                return false;
            }
            
            //如果是组合类型并且定义了绑定明细的话_重组下数据
            if($row[2] == 2){
                if(isset($row[9]) && !empty($row[9])){
                    $tmp_basicMInfos = explode('|',$row[9]);
                    foreach($tmp_basicMInfos as $tmp_basicMInfo){
                        $tmp_bnInfo = explode(':',$tmp_basicMInfo);
                        $tmp_binds[$tmp_bnInfo[0]] = $tmp_bnInfo[1];
                    }
                    unset($row[9]);
            
                    $row[9] = $tmp_binds;
                    foreach($row[9] as $bn => $val){
                        $basicInfo = $basicMaterialObj->getList('bm_id', array('material_bn'=>$bn), 0, 1);
                        if(!$basicInfo){
                            $msg['error'] = "找不到关联的基础物料：".$bn .",物料编码：". $row[1];
                            return false;
                        }else{
                            $tmp_at[$basicInfo[0]['bm_id']] = $val;
                        }
                    }
                    unset($row[9]);
                    $row[9] = $tmp_at;
                }else{
                    $msg['error'] = "组合物料请至少设置一个物料明细内容,物料编码：".$row[1];
                    return false;
                }
            }

            if($row[10] =="开启"){
                $row[10] = 1;
            }elseif($row[10] =="关闭"){
                $row[10] = 2;
            }else{
                $msg['error'] = "是否启用保质期监控的内容错误：".$row[10].",请填写开启或关闭,物料编码：". $row[1];
                return false;
            }
            
            #特殊扫码配置
            if($row[16] == "开启"){
                $row[16] = 3;
            }elseif($row[16] == "关闭"){
                $row[16] = 4;
            }else{
                $msg['error'] = "特殊扫码配置的内容错误：".$row[16].",请填写开启或关闭,物料编码：". $row[1];
                return false;
            }
            
            if($row[16] == 3)
            {
                $row[17]    = intval($row[17]);
                $row[18]    = intval($row[18]);
            }
            else
            {
                $row[17]    = 1;
                $row[18]    = 1;
            }
            
            #是否自动生成销售物料
            if($row[19] == '是'){
                $row[19] = 1;
            }elseif($row[19] == '否' || empty($row[19])){
                $row[19] = 0;
            }else{
                $msg['error'] = "是否自动生成销售物料的内容错误：".$row[16].",请填写是、否或留空,物料编码：". $row[1];
                return false;
            }
            
            if(($row[19] === 1) && ($row[4] === 2))
            {
                $msg['error'] = "开启自动生成销售物料,基础物料必须是在售状态,物料编码：". $row[1];
                return false;
            }
            
            if($row[19] === 1)
            {
                $salesMaterialItem    = $salesMaterialObj->dump(array('sales_material_bn'=>$row[1]), 'sm_id');
                if($salesMaterialItem)
                {
                    $msg['error'] = "销售物料已经存在,无法自动生成;物料编码：". $row[1];
                    return false;
                }
            }
            
            #是否全渠道
            if($row[20] =="开启"){
                $row[20] = 1;
            }elseif($row[20] =="关闭"){
                $row[20] = 2;
            }else{
                $msg['error'] = "是否全渠道填写的内容错误：".$row[20]."，请填写开启或关闭";
                return false;
            }
            
            #拼接数据
            $sdf    = array(
                        'material_name' => $row[0],
                        'material_bn' => trim($row[1]),
                        'type' => $row[2],
                        'material_code' => trim($row[3]),
                        'visibled' => $row[4],
                        'unit' => $row[5],
                        'retail_price' => $row[6] ? $row[6] : 0.00,
                        'cost' => $row[7] ? $row[7] : 0.00,
                        'weight' => $row[8] ? $row[8] : 0.00,
                        'at' => $row[9],
                        'use_expire' => $row[10],
                        'warn_day' => $row[11],
                        'quit_day' => $row[12],
                        'cat_id' => $row[13],
                        'specifications' => $row[14],
                        'brand_id' => $row[15],
                        'special_setting' => $row[16],
                        'first_num' => $row[17],
                        'last_num' => $row[18],
                        'material_bn_crc32' => '',
                        'create_material_sales' => $row[19],
                        'omnichannel' => $row[20],
            );
            
            #检查数据有效性
            $err_msg          = '';
            if(!$checkBasicLib->checkParams($sdf, $err_msg))
            {
                $msg['error']    = $err_msg .',物料编码：'. $sdf["material_bn"];
                return false;
            }
            
            $fileData['basicm']['contents'][] = $sdf;
            
            #销毁
            unset($row, $tmp_basicMInfos, $tmp_bnInfo, $tmp_binds);
            
            base_kvstore::instance('basic_material')->store('basic-'.$this->ioObj->cacheTime,$fileData);
        }
        return null;
    }

    /**
     * 完成基础物料的导入
     *
     * @param Null
     * @return Null
     */
    function finish_import_csv(){
        base_kvstore::instance('basic_material')->fetch('basic-'.$this->ioObj->cacheTime,$data);
        base_kvstore::instance('basic_material')->store('basic-'.$this->ioObj->cacheTime,'');

        $oQueue = app::get('base')->model('queue');
        $aP = $data;
        $pSdf = array();

        $count = 0;
        $limit = 50;
        $page = 0;
        $orderSdfs = array();

        foreach ($aP['basicm']['contents'] as $k => $aPi){
            if($count < $limit){
                $count ++;
            }else{
                $count = 0;
                $page ++;
            }
            $pSdf[$page][] = $aPi;
        }

        foreach($pSdf as $v){
            $queueData = array(
                'queue_title'=>'基础物料导入',
                'start_time'=>time(),
                'params'=>array(
                    'sdfdata'=>$v,
                    'app' => 'material',
                    'mdl' => 'basic_material'
                ),
                'worker'=>'material_basic_material_to_import.run',
            );
            $oQueue->save($queueData);
        }
        $oQueue->flush();
        
        //记录日志
        $operationLogObj    = app::get('ome')->model('operation_log');
        $operationLogObj->write_log('basic_material_import@wms', 0, "批量导入基础物料,本次共导入". count($aP['basicm']['contents']) ."条记录!");
        
        return null;
    }


    function fgetlist_csv(&$data,$filter,$offset,$exportType = 1)
    {
        $brand_obj = app::get('ome')->model('brand');
        $basic_material_obj = app::get('material')->model('basic_material');

        if(!$data['title']){
            $title = array();
            foreach($this->io_title('exportBasicM') as $k => $v){
                $title[] = $v;
            }
            $data['contents']['title'] = '"' . implode('","', $title) . '"';
        }

        if($filter['isSelectedAll'] && $filter['isSelectedAll'] == '_ALL_'){
            $bm_ids = $basic_material_obj->getList('bm_id', array());
            foreach($bm_ids as $key => $vals){
                $bm_ids[$key] = $vals['bm_id'];
            }
            $basic_materials = kernel::single('material_basic_material')->getBasicMaterialByBmids($bm_ids);
            foreach($basic_materials as $basic_id => $basic){
                $brand_name = $brand_obj->dump(array('brand_id' => $basic['brand_id']));
                $material_row = array();
                $material_row['*:基础物料名称'] = $basic['material_name'];
                $material_row['*:基础物料编码'] = $basic['material_bn'];
                $material_row['*:物料属性'] = $basic['type'] == '1' ? '普通' : '组合';
                $material_row['*:销售状态'] = $basic['visibled'] == '1' ? '在售' : '停售';
                $material_row['*:重量'] = $basic['weight'];
                $material_row['*:物料规格'] = $basic['specifications'];
                $material_row['*:物料品牌'] = empty($brand_name['brand_name']) ? ' - ' : $brand_name['brand_name'];
                $material_row['*:成本'] = $basic['cost'];
                $material_row['*:售价'] = $basic['retail_price'];
                $material_row['*:包装单位'] = $basic['unit'];
                $material_row['*:是否拆单'] = $basic['autosplit'] == 'true' ? '是' : '否';

                $data['contents'][] = '"' . implode('","', $material_row) . '"';
            }

        } else {
            foreach($filter['bm_id'] as $k => $v){
                $basic_material = kernel::single('material_basic_material')->getBasicMaterialExt($v);
                $brand_name = $brand_obj->dump(array('brand_id' => $basic_material['brand_id']));
                if(!$basic_material) return false;
                $material_row = array();
                $material_row['*:基础物料名称'] = $basic_material['material_name'];
                $material_row['*:基础物料编码'] = $basic_material['material_bn'];
                $material_row['*:物料属性'] = $basic_material['type'] == '1' ? '普通' : '组合';
                $material_row['*:销售状态'] = $basic_material['visibled'] == '1' ? '在售' : '停售';
                $material_row['*:重量'] = $basic_material['weight'];
                $material_row['*:物料规格'] = $basic_material['specifications'];
                $material_row['*:物料品牌'] = empty($brand_name['brand_name']) ? ' - ' : $brand_name['brand_name'];
                $material_row['*:成本'] = $basic_material['cost'];
                $material_row['*:售价'] = $basic_material['retail_price'];
                $material_row['*:包装单位'] = $basic_material['unit'];
                $material_row['*:是否拆单'] = $basic_material['autosplit'] == 'true' ? '是' : '否';
                

                $data['contents'][] = '"' . implode('","', $material_row) . '"';
            }
        }


        return false;
    }

    function searchOptions(){
        $parentOptions = parent::searchOptions();
        $childOptions = array(
            'barcode'=>app::get('ome')->_('条形码'),
        );
        return $Options = array_merge($parentOptions,$childOptions);
    }

    function _filter($filter,$tableAlias=null,$baseWhere=null){
        $codeObj = $basicMaterialCodeObj = app::get('material')->model('codebase');
        $where = array();
        $sqlstr = '';
        if($filter['barcode']){
            $bm_ids = $codeObj->dump(array('code' => $filter['barcode']), 'bm_id');
            $where[] = " bm_id in (".implode(',',$bm_ids).")";
            unset($filter['barcode']);
        }
        if($where){
            $sqlstr.=implode(' AND ',$where)." AND ";
        }
       
        return $sqlstr.parent::_filter($filter,$tableAlias,$baseWhere);
    }
}
